import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/customer'
import type { CustomerChance } from '@/types/customer'
import type { StageOption } from '@/types/customer'
import { formatDateTime } from '@/utils/format'

// 查询表单
const queryForm = reactive({
  page: 1,
  limit: 10,
  keywords: '',
  stage: '',
})

// 销售机会列表
const chanceList = ref<CustomerChance[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)

// 选中的销售机会
const selectedChances = ref<CustomerChance[]>([])

// 客户选项
const customerOptions = ref<Array<{ id: number; name: string }>>([])
// 客户远程搜索相关
const customerLoading = ref<boolean>(false)
const customerSearchKeyword = ref<string>('')

// 销售阶段选项
const stageOptions = ref<StageOption[]>([])

// 详情抽屉
const detailDrawerVisible = ref<boolean>(false)
const currentChance = ref<CustomerChance>({} as CustomerChance)

// 新增/编辑抽屉
const drawerVisible = ref<boolean>(false)
const chanceOperationMode = ref<'add' | 'edit'>('add')
const chanceForm = reactive({
  id: 0,
  title: '',
  cid: '',
  stage: 1,
  discovery_time: '',
  expected_time: '',
  expected_order_amount: 0,
  content: '',
})

// 表单验证规则
const chanceRules = {
  title: [{ required: true, message: '请输入机会名称', trigger: 'blur' }],
  cid: [{ required: true, message: '请选择客户', trigger: 'change' }],
  stage: [{ required: true, message: '请选择阶段', trigger: 'change' }],
}

// 表单引用
const chanceFormRef = ref<any>(null)
const queryFormRef = ref<any>(null)

// 加载客户选项 - 使用远程搜索时不再需要提前加载所有客户
const loadCustomerOptions = async () => {
  // 保留函数体但不再使用
  console.log('使用远程搜索加载客户数据')
}

// 远程搜索客户
const remoteSearchCustomers = async (query: string) => {
  if (query.trim() === '') {
    customerOptions.value = []
    return
  }

  customerLoading.value = true
  customerSearchKeyword.value = query

  try {
    const response = await customerApi.searchCustomers(query.trim())
    if (response && response.code === 0) {
      customerOptions.value = response.data || []
    } else {
      customerOptions.value = []
      console.error('搜索客户失败:', response?.msg)
    }
  } catch (error) {
    customerOptions.value = []
    console.error('搜索客户失败:', error)
  } finally {
    customerLoading.value = false
  }
}

// 加载销售阶段选项
const loadStageOptions = async () => {
  try {
    const response = await customerApi.getChanceStageOptions()
    if (response && response.code === 0) {
      stageOptions.value = response.data || []
    } else {
      console.error('获取销售阶段选项失败:', response?.msg)
      // 如果获取失败，使用默认选项
      stageOptions.value = [
        { id: 1, title: '初步接触' },
        { id: 2, title: '需求分析' },
        { id: 3, title: '方案报价' },
        { id: 4, title: '商务谈判' },
        { id: 5, title: '成交' },
        { id: 6, title: '失败' },
      ]
    }
  } catch (error) {
    console.error('获取销售阶段选项失败:', error)
    // 如果获取失败，使用默认选项
    stageOptions.value = [
      { id: 1, title: '初步接触' },
      { id: 2, title: '需求分析' },
      { id: 3, title: '方案报价' },
      { id: 4, title: '商务谈判' },
      { id: 5, title: '成交' },
      { id: 6, title: '失败' },
    ]
  }
}

// 处理查询
const handleSearch = async () => {
  loading.value = true
  try {
    const params: any = {
      page: queryForm.page,
      limit: queryForm.limit,
    }

    if (queryForm.keywords) {
      params.keywords = queryForm.keywords
    }

    if (queryForm.stage) {
      params.stage = queryForm.stage
    }

    const response = await customerApi.getChanceList(params)
    if (response && response.code === 0) {
      chanceList.value = response.data || []
      total.value = response.count || 0
    } else {
      chanceList.value = []
      total.value = 0
      ElMessage.error(response?.msg || '获取销售机会列表失败')
    }
  } catch (error) {
    chanceList.value = []
    total.value = 0
    console.error('获取销售机会列表失败:', error)
    ElMessage.error('获取销售机会列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  queryForm.keywords = ''
  queryForm.stage = ''
  queryForm.page = 1
  handleSearch()
}

// 新增销售机会
const handleAdd = () => {
  chanceOperationMode.value = 'add'
  // 重置表单
  chanceForm.id = 0
  chanceForm.title = ''
  chanceForm.cid = ''
  chanceForm.stage = 1
  chanceForm.discovery_time = ''
  chanceForm.expected_time = ''
  chanceForm.expected_order_amount = 0
  chanceForm.content = ''

  drawerVisible.value = true
}

// 编辑销售机会
const handleEdit = (row: CustomerChance) => {
  chanceOperationMode.value = 'edit'
  // 填充表单数据
  chanceForm.id = row.id
  chanceForm.title = row.title
  chanceForm.cid = row.cid.toString() // 转换为字符串以匹配表单类型
  chanceForm.stage = row.stage
  // 发现时间和预计成交时间直接使用，不需要转换
  chanceForm.discovery_time = row.discovery_time ? row.discovery_time.toString() : ''
  chanceForm.expected_time = row.expected_time ? row.expected_time.toString() : ''
  chanceForm.expected_order_amount = row.expected_order_amount
  chanceForm.content = row.content

  // 如果有客户名称，直接添加到选项中
  // 注意：CustomerChance类型可能没有customer_name属性，需要根据实际情况调整
  // 这里假设接口返回的数据包含customer_name字段
  if (row.hasOwnProperty('customer_name') && row.cid) {
    // 确保客户选项中包含当前客户
    const existingOption = customerOptions.value.find(option => option.id === row.cid)
    if (!existingOption) {
      customerOptions.value.push({
        id: row.cid,
        name: (row as any).customer_name, // 使用类型断言访问可能不存在的属性
      })
    }
  }

  drawerVisible.value = true
}

// 查看销售机会详情
const handleView = (row: CustomerChance) => {
  currentChance.value = { ...row }
  detailDrawerVisible.value = true
}

// 删除销售机会
const handleDelete = (row: CustomerChance) => {
  ElMessageBox.confirm(`确定要删除销售机会"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await customerApi.deleteCustomerChance(row.id)
        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          handleSearch()
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除销售机会失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 批量删除销售机会
const handleBatchDelete = () => {
  if (selectedChances.value.length === 0) {
    ElMessage.warning('请先选择要删除的销售机会')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的${selectedChances.value.length}个销售机会吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const ids = selectedChances.value.map(item => item.id)
        // 这里需要根据实际API调整批量删除的实现
        const deletePromises = ids.map(id => customerApi.deleteCustomerChance(id))
        const results = await Promise.all(deletePromises)

        // 检查所有删除操作是否都成功
        const allSuccess = results.every((result: any) => result && result.code === 0)

        if (allSuccess) {
          ElMessage.success('批量删除成功')
          handleSearch()
        } else {
          ElMessage.error('部分删除失败')
          handleSearch()
        }
      } catch (error) {
        console.error('批量删除销售机会失败:', error)
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 处理选择变化
const handleSelectionChange = (selection: CustomerChance[]) => {
  selectedChances.value = selection
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  queryForm.page = 1
  handleSearch()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  handleSearch()
}

// 关闭详情抽屉
const closeDetailDrawer = (done?: () => void) => {
  if (done) done()
  else detailDrawerVisible.value = false
}

// 关闭新增/编辑抽屉
const closeDrawer = (done?: () => void) => {
  drawerVisible.value = false
  if (chanceFormRef.value) {
    chanceFormRef.value.resetFields()
  }
}

// 提交表单
const handleSubmit = () => {
  if (chanceFormRef.value) {
    chanceFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 创建不包含id的formData副本
          const { id, ...formData } = {
            ...chanceForm,
            cid: parseInt(chanceForm.cid as string),
            // 修正：将毫秒级时间戳转换为秒级时间戳
            discovery_time: chanceForm.discovery_time
              ? Math.floor(parseInt(chanceForm.discovery_time as string) / 1000)
              : 0,
            expected_time: chanceForm.expected_time
              ? Math.floor(parseInt(chanceForm.expected_time as string) / 1000)
              : 0,
          }

          let response
          if (chanceOperationMode.value === 'add') {
            response = await customerApi.addCustomerChance(formData)
          } else {
            // 编辑时需要传递id参数
            response = await customerApi.editCustomerChance({ id: chanceForm.id, ...formData })
          }

          if (response && response.code === 0) {
            ElMessage.success(chanceOperationMode.value === 'add' ? '新增成功' : '编辑成功')
            drawerVisible.value = false
            handleSearch()
          } else {
            ElMessage.error(
              response?.msg || (chanceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
            )
          }
        } catch (error) {
          console.error('保存销售机会失败:', error)
          ElMessage.error(chanceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
        }
      }
    })
  }
}

// 初始化加载
const initLoad = () => {
  // 使用立即执行的异步函数来加载数据
  ;(async () => {
    // 加载销售阶段选项
    await loadStageOptions()
    // 加载销售机会列表
    handleSearch()
  })()
}

// 格式化日期函数（仅显示日期部分）
const formatDateOnly = (date: number | string): string => {
  if (!date) return '-'
  // 使用已有的formatDateTime函数，但只显示日期部分
  return formatDateTime(date).split(' ')[0]
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  queryForm,
  chanceList,
  total,
  loading,
  selectedChances,
  detailDrawerVisible,
  currentChance,
  drawerVisible,
  chanceOperationMode,
  chanceForm,
  chanceRules,
  customerOptions,
  customerLoading,
  stageOptions,
  chanceFormRef,
  queryFormRef,

  // 方法
  handleSearch,
  handleReset,
  handleAdd,
  handleEdit,
  handleView,
  handleDelete,
  handleBatchDelete,
  handleSelectionChange,
  handleSizeChange,
  handleCurrentChange,
  closeDetailDrawer,
  closeDrawer,
  handleSubmit,
  loadCustomerOptions,
  remoteSearchCustomers,
  formatDateTime,
  formatDateOnly, // 新增的日期格式化函数
  initLoad,
}
